//
//  NSArray+ACCommon.m
//  AcmedcareCore
//
//  Created by AcZx on 2018/3/9.
//

#import "NSArray+ACCommon.h"

@implementation NSArray (ACCommon)

/**
 * 大数组拆分成小数组(逐个放入)
 */
- (NSArray*)changeArrayWithIndex:(int)index{
    
    if (self.count <= 0 || index <= 0) {
        return self;
    }
    NSMutableArray *arrTotal = [[NSMutableArray alloc]init];
    for (int x = 0; x < index; x++) {
        NSMutableArray *subArr = [[NSMutableArray alloc]init];
        for (int m = 0;  m < self.count; m ++) {
            if (m % index == x) {
                [subArr addObject:self[m]];
            }
        }
        [arrTotal addObject:subArr];
    }
    return [arrTotal copy];
}

/**
 * plist 文件转数组
 */
+ (NSArray *)arrayWithPlistData:(NSData *)plist{
    if (!plist) return nil;
    NSArray *array = [NSPropertyListSerialization propertyListWithData:plist options:NSPropertyListImmutable format:NULL error:NULL];
    if ([array isKindOfClass:[NSArray class]]) return array;
    return nil;
}

+ (NSArray *)arrayWithPlistString:(NSString *)plist {
    if (!plist) return nil;
    NSData *data = [plist dataUsingEncoding:NSUTF8StringEncoding];
    return [self arrayWithPlistData:data];
}

/**
 * 数组打乱
 */
- (id)randomObject {
    if (self.count) {
        return self[arc4random_uniform((u_int32_t)self.count)];
    }
    return nil;
}

- (NSString *)jsonPrettyStringEncoded {
    if ([NSJSONSerialization isValidJSONObject:self]) {
        NSError *error = nil;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self options:NSJSONWritingPrettyPrinted error:&error];
        NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        if (!error) return json;
    }
    return nil;
}

@end







@implementation NSMutableArray (ACCommon)

/**
 * plist 文件转数组
 */
+ (NSMutableArray *)arrayWithPlistData:(NSData *)plist {
    if (!plist) return nil;
    NSMutableArray *array = [NSPropertyListSerialization propertyListWithData:plist options:NSPropertyListMutableContainersAndLeaves format:NULL error:NULL];
    if ([array isKindOfClass:[NSMutableArray class]]) return array;
    return nil;
}

+ (NSMutableArray *)arrayWithPlistString:(NSString *)plist {
    if (!plist) return nil;
    NSData *data = [plist dataUsingEncoding:NSUTF8StringEncoding];
    return [self arrayWithPlistData:data];
}

- (void)insertObjects:(NSArray *)objects atIndex:(NSUInteger)index {
    NSUInteger i = index;
    for (id obj in objects) {
        [self insertObject:obj atIndex:i++];
    }
}

/**
 * 数组颠倒
 */
- (void)reverse {
    NSUInteger count = self.count;
    int mid = floor(count / 2.0);
    for (NSUInteger i = 0; i < mid; i++) {
        [self exchangeObjectAtIndex:i withObjectAtIndex:(count - (i + 1))];
    }
}

/**
 * 数组打乱
 */
- (void)shuffle {
    for (NSUInteger i = self.count; i > 1; i--) {
        [self exchangeObjectAtIndex:(i - 1)
                  withObjectAtIndex:arc4random_uniform((u_int32_t)i)];
    }
}


@end



